#!/usr/bin/env python
# encoding: utf-8

import os
import logging
from logging.handlers import RotatingFileHandler

LEVELS = logging._nameToLevel

base_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
LOG_PATH = base_path + os.sep + "log"
LOG_LEVEL = "INFO"
LOG_BACKUP_COUNT = 50

if not os.path.exists(LOG_PATH):
    os.makedirs(LOG_PATH)


class LogHandler(logging.Logger):
    sh = logging.StreamHandler()

    def __init__(self, name, path=LOG_PATH, level=LOG_LEVEL, backupCount=LOG_BACKUP_COUNT):
        super(LogHandler, self).__init__(name, level)
        if not self.handlers:
            _filename = os.path.join(path, "{}.log".format(name))
            self._fh = RotatingFileHandler(filename=_filename, maxBytes=10 * 1024 * 1024, backupCount=backupCount, encoding="utf-8")
            self._fh.setLevel(level)
            formatter = logging.Formatter("[%(asctime)s] - [%(process)d] - [%(levelname)s] - [%(filename)s:%(lineno)d] %(message)s", "%Y-%m-%d %H:%M:%S")
            self._fh.setFormatter(formatter)
            self.addHandler(self._fh)

    def __del__(self):
        self._fh.close()

    def info(self, msg, *args, **kwargs):
        self.fontColor("\033[0;37m%s\033[0m")
        if self.isEnabledFor(logging.INFO):
            self._log(logging.INFO, msg, args, **kwargs)

    def debug(self, msg, *args, **kwargs):
        self.fontColor("\033[0;36m%s\033[0m")
        if self.isEnabledFor(logging.DEBUG):
            self._log(logging.DEBUG, msg, args, **kwargs)

    def warn(self, msg, *args, **kwargs):
        self.fontColor("\033[0;33m%s\033[0m")
        if self.isEnabledFor(logging.WARNING):
            self._log(logging.WARNING, msg, args, **kwargs)

    def error(self, msg, *args, **kwargs):
        self.fontColor("\033[0;31m%s\033[0m")
        if self.isEnabledFor(logging.ERROR):
            self._log(logging.ERROR, msg, args, **kwargs)

    def critical(self, msg, *args, **kwargs):
        self.fontColor("\033[0;35m%s\033[0m")
        if self.isEnabledFor(logging.CRITICAL):
            self._log(logging.CRITICAL, msg, args, **kwargs)

    def exception(self, msg, *args, **kwargs):
        self.fontColor("\033[0;31m%s\033[0m")
        self._log(logging.ERROR, msg, args, **kwargs)

    def fontColor(self, color):
        # 不同的日志输出不同的颜色
        formatter = logging.Formatter(color % "[%(asctime)s] - [%(process)d] - [%(levelname)s] - [%(filename)s:%(lineno)d] %(message)s", "%Y-%m-%d %H:%M:%S")
        self.sh.setFormatter(formatter)
        self.addHandler(self.sh)
        self.sh.close()
